package setting

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gormLog "gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"os"
	"vicente-gin/common"
	"vicente-gin/dao"
)

func InitDb() {
	switch common.CONFIG.System.DBType {
	case "mysql":
		InitMysql()
	/*case "pgsql":
		GormPgSql()
	case "oracle":
		GormOracle()*/
	default:
		InitMysql()
	}

}

func InitMysql() {
	sql := common.CONFIG.Mysql
	fmt.Println("---------------------------------sql---------------------")
	fmt.Println(sql)
	dsn := sql.Username + ":" + sql.Password + "@(" + sql.Path + ")/" + sql.Dbname + "?" + sql.Config
	db, err := gorm.Open(mysql.Open(dsn),
		&gorm.Config{
			Logger: gormLog.Default.LogMode(gormLog.Info),
			NamingStrategy: schema.NamingStrategy{
				//TablePrefix:   "t_", // 表名前缀，`User`表为`t_users`
				SingularTable: true, // 使用单数表名，启用该选项后，`User` 表将是`user`
			},
		},
	)
	if err != nil {
		common.LOG.Error("DefaultDB 数据库启动异常", zap.Any("err", err))
		os.Exit(1)
	} else {
		common.DB = db
		sqlDB, err := db.DB()
		if err != nil {
			fmt.Print(err.Error())
		}
		sqlDB.SetMaxIdleConns(sql.MaxIdleConns)
		sqlDB.SetMaxOpenConns(sql.MaxOpenConns)
		sqlDB.SetConnMaxLifetime(-1)
		DBTableMigrate()
	}

}
func DBTableMigrate() {
	//db.Set("gorm:table_options","ENGINE=InnoDB").CreateTable(&User{})
	common.DB.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4").AutoMigrate(
		dao.SysUser{}, // 用户
	)
	fmt.Println("register table success")
}
